package com.fuful.service;

import com.fuful.domain.Cart;
import com.fuful.domain.Product;
import com.fuful.domain.Users;
import com.fuful.tools.DBHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CartService {
    private String sql = "";
    public boolean addCart(Cart parCart){
        sql = "insert into carts(uid,pid,pnum)values(" +
                parCart.getUid().getUid() +
                ","+ parCart.getPid().getPid() +
                ","+ parCart.getPnum() +")";
        int flag = DBHelper.executeUpdata(sql);
        if(flag <= 0){
            return false;
        }
        return true;
    }

    public List<Cart> getMyCart(Users users){
        sql = "SELECT c.cid,c.pid,p.pname,p.pprice,c.pnum " +
                "FROM carts c INNER JOIN products p on c.pid=p.pid " +
                "WHERE c.uid = " + users.getUid();
        List<Map<String,Object>> data = DBHelper.query(sql);
        List<Cart> carts = new ArrayList<>();
        for (Map<String,Object> row : data) {
            int cid = Integer.parseInt(row.get("cid").toString());
            int pid = Integer.parseInt(row.get("pid").toString());
            float pprice = Float.parseFloat(row.get("pprice").toString());
            String pname = row.get("pname").toString();
            int pnum = Integer.parseInt(row.get("pnum").toString());
            Product product = new Product(pid,pname,pprice);
            Cart cart = new Cart(cid,users,product,pnum);
            carts.add(cart);
        }
        return carts;
    }

}
